﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using ESRI.ArcGIS.Geodatabase;

namespace Tayninh2011
{
    public sealed partial class FrmLogin : RootForm
    {
        public delegate void addItem();
        public delegate void AdVance();
        public delegate void Connectdelegate();
        public addItem myDelegate;
        public AdVance advanceDel;
        //public Connectdelegate ConnectDel();
        private Thread threadMy;
        private Thread threadAdance;
        private Thread threadConnect;
        private static bool _boolConnectionStatus;
        private static readonly FrmLogin meForm = new FrmLogin();
        private FrmCash frmCash = FrmCash.CallMe;
        ITnUtilitiesFile fileUtil = new TnUtilities();
        private IVersionedWorkspace vWp = null;
        //private IWorkspaceEdit _sdeWorkspaceEdit;
        //private IWorkspace _mdbWorkspace;
        //private string _sdeEnvironment = "";
        //private string _serverName = "";
        //private string _database = "";
        //private string strXmlFileName = "userInfo";
        //private string[,] _arrUserInfo;
        //private string _strPathTempFolder = "C:/tayninh/temp";
        //private string _strNameTempMdbFile = "tempmdb";
        //private SqlConnection _sqlConnection;
        //private string 
        //FrmMain frmMain = FrmMain.FormMain;
        //FrmCash frmMain2 = FrmCash.CallMe;
        //FrmMap frmMap = FrmMap.FormMap;
        //FrmMainMain frmMainMain = FrmMainMain.CallMe;

        //public string SdeEnvironment
        //{
        //    get { return _sdeEnvironment; }
        //    set { _sdeEnvironment = value; }
        //}
        public bool BoolConnectionStatus
        {
            get { return _boolConnectionStatus; }
            set { _boolConnectionStatus = value; }
        }
        private FrmLogin()
        {
            InitializeComponent();
            //tbxServer.Text = TnServerProperties.SERVER_NAME;
            cbxVersion.Items.Add("sde.DEFAULT");
            cbxVersion.Items.Add("dbo.DEFAULT");
            cbxVersion.SelectedIndex = 0;
            this.Height = 197;
            myDelegate = new addItem(add);
            advanceDel = new AdVance(advance);
            try
            {
                
                if (System.IO.File.Exists(RootForm._strXmlUserFileName + ".xml"))
                {
                    RootForm._arrUserInfo = fileUtil.ReadUserInfoFromXmlFile(RootForm._strXmlUserFileName, "");
                    this.tbxServer.Text = RootForm._arrUserInfo[0, 1];
                    this.tbxDatabase.Text = RootForm._arrUserInfo[1, 1];
                    this.tbxUser.Text = RootForm._arrUserInfo[2, 1];
                    this.tbxPass.Text = RootForm._arrUserInfo[3, 1];
                }
                //lblSQLVer.Text ="SQL "+ TnServerProperties.SQL_EDITION;
            }
            catch (Exception e) { MessageBox.Show(e.ToString()); }


        }
        private void add()
        {
            String myItem;
            for (int i = 1; i < 6; i++)
            {
                myItem = "MyListItem" + i.ToString();
                this.cbxVersion.Items.Add(myItem);
                this.cbxVersion.Update();
                Thread.Sleep(10);
            }
        }
        private void ThreadFunction()
        {
            TnThreadClassFrmLogin myThreadClassObject = new TnThreadClassFrmLogin(this);
            myThreadClassObject.Run(myDelegate);
        }
        private void ThreadAdvance()
        {
            TnThreadClassFrmLogin adVanceThreadClassObject = new TnThreadClassFrmLogin(this);
            adVanceThreadClassObject.Run(advanceDel);
        }
        public static FrmLogin CallMe
        {
            get {
                return meForm; }
        }
        public new void Show()
        {
            if (isShown)
            {
                base.Show();
            }
            else
            {
                base.Show();
                isShown = true;
            }
        }
        public new void ShowDialog()
        {
            if (isShown)
            {
                base.ShowDialog();
            }
            else
            {
                base.ShowDialog();
                isShown = true;
            }
        }
        private static bool isShown = false;
        static FrmLogin()
        {

            meForm.FormClosing += new FormClosingEventHandler(frmLogin_FormClosing);

        }
        private static void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {

            e.Cancel = true;
            isShown = false;
            if (meForm.BoolConnectionStatus == true)
            {
                meForm.Hide();
                //frmMain.Enabled = true;
                //frmMain.TopLevel = true;
            }
            else
            {
                Application.ExitThread();
                Application.Exit();
                //frmMain.Close();
            }
            
        }
        private static int isAdvance = 0;

        private void advance()
        {
            int y = meForm.Location.Y;
            //this.Location.Y = 2;
            if (isAdvance == 0)
            {
                while (this.Height < 296)
                {
                    meForm.Height += 4;
                    //i++;
                    //if (i % 2 == 1)
                    //{
                    y -= 2;
                    //}
                    meForm.Location = new Point(meForm.Location.X, y);

                    Application.DoEvents();
                }


            }
            if (isAdvance == 1)
            {
                //MessageBox.Show("hehe");
                while (meForm.Height > 201)
                {
                    meForm.Height -= 4;
                    //i++;
                    //if (i % 2 == 1)
                    //{
                    y += 2;
                    //}
                    meForm.Location = new Point(meForm.Location.X, y);
                    Application.DoEvents();
                }
                isAdvance = 0;
            }
            if (meForm.Height > 201)
            {
                isAdvance = 1;
            }
            Thread.Sleep(10);
        }
        private void btnAdvance_Click(object sender, EventArgs e)
        {
            threadMy = new Thread(new ThreadStart(ThreadFunction));
            threadAdance = new Thread(new ThreadStart(ThreadAdvance));
            //myThread.Start();
            threadAdance.Start();
            //myThread.Join();
            //advanceThread.Join();

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            if (this.BoolConnectionStatus == true)
            {

                this.Hide();

                //frmMain.Enabled = true;
                //frmMain.TopLevel = true;
            }
            else
            {
                Application.ExitThread();
                Application.Exit();
                //frmMain.Close();
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string strServer = tbxServer.Text;
            string strInstance = tbxInstance.Text;
            string strDatabase = tbxDatabase.Text;
            string strAuthen = "sql";
            string strVersion = "sde.DEFAULT";
            string strUser = tbxUser.Text;
            string strPass = tbxPass.Text;

            //frmMain = (FrmMain)this.MdiParent;
            try
            {
                //if (cbxVersion.SelectedIndex == 0)
                //{
                //    strVersion = "sde.DEFAULT";
                //}
                //else
                //{
                //    strVersion = "dbo.DEFAULT";
                //}
                //Thread t = new Thread(new ThreadStart(threadConnect));
                //t.Start();

                //ITnUtilitiesFile fileUti = new TnUtilities();

                strVersion = cbxVersion.Text;
                ITnToolsWorkspace wspTool = new TnTools();
                RootForm._sdeWorkspace = wspTool.CreateWorkspaceSDE(strServer, strInstance, strAuthen, strDatabase, "sde.TN", strUser, strPass);
                RootForm._sdeEnvironment = "Database Connections/Connection to " + strServer +"."+ RootForm._strVersionTail;// ".sde";
                //funcOpenConnectionSDE_dbo(strServer, strInstance, strDatabase);
                //lblStatus.Text = "ket noi thanh cong";
                //frmMain.StrConnectionStatus = "CONNECTION_OK";

                //t.Join();
                //this.Cursor = Cursors.Default;

                //lblStatus.ForeColor = Color.Green;

                BoolConnectionStatus = true;
                //ghi vao file xml
                string[,] arrInfo = new string[,] { { "server", strServer }, { "database", strDatabase }, { "uid", strUser }, { "pwd", strPass } };
                string connectionString = "server=" + strServer + "; database=" + strDatabase + "; uid=" + strUser + "; pwd=" + strPass + ";";
                //RootForm._sqlConnection = new SqlConnection(connectionString);
                //RootForm._sqlConnection.Open();
                fileUtil.CreateXmlFile("sde", arrInfo, "userInfo", "");
                //RootForm a = (RootForm)frmMain2;
                //RootForm formMain = (RootForm)frmMainMain;
                //RootForm formMap = (RootForm)frmMap;


                //sendInfo(ref a);
                //sendInfo(ref formMain);
                //sendInfo(ref formMap);
                try
                {
                    if (!System.IO.File.Exists(_strPathTempFolder + "/" + _strNameTempMdbFile + ".mdb"))
                    {
                        ITnToolsWorkspace createTempWsp = new TnTools();
                        _mdbWorkspace = createTempWsp.CreateWorkspaceGdbFile(_strPathTempFolder, _strNameTempMdbFile, "mdb");
                    }
                }
                catch { }
                RootForm.CalcTool3010 = RootForm.CalcFactory.GetCalculator(EnumModeCalc.mode3010);
                RootForm.CalcTool3020 = RootForm.CalcFactory.GetCalculator(EnumModeCalc.mode3020);
                RootForm.CalcTool31xx32xx = RootForm.CalcFactory.GetCalculator(EnumModeCalc.mode31xxAnd32xx);

                vWp = (IVersionedWorkspace)RootForm._sdeWorkspace;
                IVersion parentVersion = null;
                try
                {
                    parentVersion = vWp.FindVersion("sde.TN");
                    //parentVersion.Delete();
                }
                catch { }
                //parentVersion = vWp.FindVersion("sde.DEFAULT");
                IVersion childVersion = null;
                //childVersion = parentVersion.CreateVersion("TN");
                //childVersion.Access = esriVersionAccess.esriVersionAccessProtected;
                IVersionInfo ifo = null;
                ifo = vWp.Versions.Next();
                while (ifo != null)
                {
                    MessageBox.Show(ifo.Children.Next().VersionName);
                    ifo = vWp.Versions.Next();
                }
                //MessageBox.Show(childVersion.VersionInfo.VersionName);
                
                frmCash.Show();

                //RootForm.CalcFactory.SetParams(RootForm._sdeWorkspace, RootForm._sdeEnvironment, RootForm._arrUserInfo);
                modeApp = TnModeApp.MAIN_APP_SQL_2008_ENTERPRISE;
                IsSeeOnly = false;
                //formMap.Show();
                //formMap.Hide();
                //frmMainMain.Show();
                //frmMain.SetConnectionStatus("Đã kết nối", BoolConnectionStatus);
                //frmMain.SdeEnvironment = this.SdeEnvironment;
                //frmMain.SetWorkspace(this._sdeWorkspaceEdit);
                //frmMain.SetUserInfo(this._arrUserInfo);
                //frmMain.SqlConnection = this._sqlConnection;
                //frmMain.Enabled = true;
                //frmMain.TopLevel = true;
                //frmMain2.Show();
                this.Hide();
                FrmInit.CallMe.Hide();
                //_connecting = true;
            }
            catch (Exception e1)
            {
                BoolConnectionStatus = false;
                //lblStatus.Text = "khong ket noi duoc";
                //this.StrConnectionStatus = "CONNECTION_ERROR";
                //lblStatus.ForeColor = Color.Red;
                //MessageBox.Show(e1.ToString());
                //frmMain.SetWorkspace(null);
                //_connecting = false;
                if (MessageBox.Show("Không đăng nhập được \n Thoát khỏi chương trình: chọn No \n Tiếp tục nhưng không tương tác dữ liệu: chọn Yes \n Đăng nhập lại: chọn Cancel", "Lỗi đăng nhập", MessageBoxButtons.YesNoCancel) == DialogResult.No)
                {
                    this.Close();
                }
                //else if (MessageBox.Show("Thoát khỏi chương trình: chọn Yes \n Tiếp tục nhưng không tương tác dữ liệu: chọn No \n Đăng nhập lại: chọn Cancel", "Thoát", MessageBoxButtons.YesNoCancel) == DialogResult.Cancel)
                //{

                //}
            }
            finally
            {
                //frmMain.StrConnectionStatus = this.StrConnectionStatus;
                //frmMain.SetConnectionStatus(this.StrConnectionStatus);
                //this.StrDatabase = this.tbxDatabase.Text;
                //frmMain.SetDatabase(this.StrDatabase);
            }
        }
        private void connect()
        {
            RootForm._sdeEnvironment = "Database Connections/Connection to " + tbxServer.Text + "."+RootForm._strVersionTail;
            this.Cursor = Cursors.WaitCursor;
        }
        //private void sendInfo(ref RootForm form)
        //{
        //    form.SdeEnvironment = RootForm._sdeEnvironment;
        //    form.SdeWorkspace = RootForm._sdeWorkspace;
        //    form.UserInfo = this._arrUserInfo;
        //}

        private void button1_Click(object sender, EventArgs e)
        {
            //congty ct = new congty();
            //ct.Show();
        }

        private void cbxVersion_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbxVersion.Text)
            {
                case "sde.DEFAULT":
                    RootForm._strVersionTail = "sde";
                    break;
                case "dbo.DEFAULT":
                    RootForm._strVersionTail = "dbo";
                    break;
                default:
                    RootForm._strVersionTail = "sde";
                    break;
            }
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {

        }
    }
}
